<?php

declare (strict_types=1);

namespace app\order\model;

use app\activityNew\model\ImsEweiShopActivity;
use think\admin\Model;
use think\model\relation\HasOne;
use app\order\model\ImsEweiShopOrderGoods;
use app\member\model\ImsEweiShopMemberCart;
use app\member\model\ImsEweiShopMemberAddress;
use app\wechat\service\WechatService;
use EasyWeChat\MiniApp\Application;
use app\wechat\model\WechatPaymentRecord;

/**
 * 访问统计
 * @class ImsEweiShopOrder
 * @package think\admin\model
 */

class ImsEweiShopOrder extends Model
{
    protected $createTime = 'createtime';
    protected $updateTime = false;

    /**
     * 日志名称
     * @var string
     */
    protected $oplogName = 'order管理';

    /**
     * 商户信息管理
     * @var string
     */
    protected $oplogType = 'order管理';

    public static function creatOrder($datas,$member){
        if (empty($datas['cart_ids'])) {
            return ['code'=>1,'message'=>'购物车商品'];
        }

        if (empty($datas['address_id'])) {
            return ['code'=>2,'message'=>'请选择地址'];
        }

        $address = ImsEweiShopMemberAddress::mk()->where(['id'=>$datas['address_id']])->find()->toArray();

        if (empty($datas['pay_type'])) {
            return ['code'=>3,'message'=>'请选择支付方式'];
        }
        $makeorderstatus = 0;
        $allgoods = array();
        $task_reward_goods = array();
        $tgoods = array();
        $totalprice = 0;
        $goodsprice = 0;
        $grprice = 0;
        $weight = 0;
        $taskdiscountprice = 0;
        $lotterydiscountprice = 0;
        $discountprice = 0;
        $isdiscountprice = 0;
        $merchisdiscountprice = 0;
        $cash = 1;
        $deductprice = 0;
        $deductprice2 = 0;
        $virtualsales = 0;
        $dispatch_price = 0;
        $seckill_price = 0;
        $seckill_payprice = 0;
        $seckill_dispatchprice = 0;
        $buyagain_sale = true;
        $buyagainprice = 0;
        $saleset = false;
        $isvirtual = false;
        $isverify = false;
        $isonlyverifygoods = true;
        $isendtime = 0;
        $endtime = 0;
        $verifytype = 0;
        $isvirtualsend = false;
        $couponmerchid = 0;
        $total_array = array();
        if (is_array($datas['cart_ids'])) {
            $carWhere = [
                'f.openid' => $member['openid'],
                'f.deleted' => 0,
                'f.id' => $datas['cart_ids']
            ];

            $fields = " f.id,f.selected AS `select`,f.goodsid,f.total AS goods_number,g.thumb,g.parent_gid,g.parent_merchid,g.title,g.subtitle,g.total AS number_stock,g.marketprice,g.merchid,g.goodssn,g.productsn,g.marketprice AS price,g.service_fee_type,g.service_fee_per,g.costprice,g.costnum,g.isdiscount ";
            $cart_list = ImsEweiShopMemberCart::mk()->alias('f')->leftJoin('ims_ewei_shop_goods g ','f.goodsid = g.id')->field($fields)->where($carWhere)->select()->toArray();
            if (empty($cart_list) || !is_array($cart_list)) {
                return ['code'=>4,'message'=>'未找到任何商品'];
            }
            foreach ($cart_list as $k => $v) {
                if($v['number_stock'] <= 0){
                    return ['code'=>5,'message'=>'请删除购物车已售罄商品'];
                }
                $allgoods[$v['merchid']][] = $v;
            }
        }else{
            return ['code'=>6,'message'=>'请刷新购物车'];
        }
        // 启动事务
        static::mk()->startTrans();
        try {
            if (count($allgoods)>1) {
                // 需要创建父订单以便支付
                $totalprice = 0;
                $totalpriceact = 0;
                foreach ($allgoods as $key => $goods) {
                    foreach ($goods as $k => $g) {
                        $totalprice += $g['marketprice']*$g['goods_number'];
						if($g['isdiscount']==1){
    						//参加活动的商品金额
    						$totalpriceact += $g['marketprice']*$g['goods_number'];
    					}
                    }
                }
                $goodsprice = $totalprice;

				$goodspriceact = $totalpriceact;

				$weigoodsprice = $totalprice - $totalpriceact;

				$actinfo  = ImsEweiShopActivity::mk()->where(['actstatus'=>1,'delete'=>0])->find();
				if(!empty($actinfo) && $actinfo['acttype']==1){
					if($goodspriceact>$actinfo['actcount']){
                        $discountprice = $actinfo['actdiscount'];
						$goodsprice =  $goodspric - $actinfo['actdiscount'];
					}elseif($actinfo['acttype']==2){
						$goodsprice = $weigoodsprice + $totalpriceact * $actinfo['actdiscount'];
                        $discountprice = $totalpriceact * $actinfo['actdiscount'];
					}
				}

                $order = [];
                $ordersn = self::createNO("ordersn", "PME");

                $order["driver_id"] = 0;
                $order["ismerch"] = 1;
                $order["parentid"] = 0;
                $order["uniacid"] = 2;
                $order["openid"] = $member['openid'];
                $order["ordersn"] = $ordersn;
                $order["price"] = $totalprice;
                $order["oldprice"] = $totalprice;
                $order["grprice"] = $totalprice;
                $order["taskdiscountprice"] = 0;
                $order["lotterydiscountprice"] = 0;
                $order["discountprice"] = $discountprice;
                $order["isdiscountprice"] = $isdiscountprice;
                $order["merchisdiscountprice"] = $merchisdiscountprice;
                $order["dispatchprice"] = 0;
                $order["cash"] = 0;
                $order["status"] = 0;
                $order["remark"] = trim($datas["remark"]);
                $order["addressid"] = !empty($datas['address_id']) ? $datas['address_id'] : 0;
                $order["goodsprice"] = $goodsprice;
                $order["dispatchtype"] = 0;
                $order["dispatchid"] = 0;
                $order["storeid"] = 0;
                $order["carrier"] = iserializer($cart_list);
                $order["createtime"] = time();
                $order["olddispatchprice"] = 0;
                $order["contype"] = 0;
                $order["couponid"] = 0;
                $order["wxid"] = 0;
                $order["wxcardid"] = 0;
                $order["wxcode"] = '';
                $order["couponmerchid"] = 0;
                $order["paytype"] = 0;
                $order["deductprice"] = 0;
                $order["deductcredit"] = 0;
                $order["deductcredit2"] = 0;
                $order["deductenough"] = 0;
                $order["merchdeductenough"] = 0 ;
                $order["couponprice"] = 0;
                $order["merchshow"] = 1;
                $order["buyagainprice"] = 0;
                $order["ispackage"] = 0;
                $order["packageid"] = 0;
                $order["seckilldiscountprice"] = $seckill_price;
                $order["quickid"] = 0;
                $order["officcode"] = 0;
                $order["liveid"] = 0;
                $order["merchid"] = 0;
                $order["isparent"] = 1;
                $order["transid"] = 0;
                $order["isverify"] = $isverify ? 1 : 0;
                $order["verifytype"] = $verifytype;
                $order["verifyendtime"] = $endtime;
                $order["verifycode"] = '';
                $order["verifycodes"] = '';
                $order["verifyinfo"] = iserializer([]);
                $order["virtual"] = 0;
                $order["isvirtual"] = $isvirtual ? 1 : 0;
                $order["isvirtualsend"] = $isvirtualsend ? 1 : 0;
                $order["invoicename"] = '';
                $order["coupongoodprice"] = 1;
                $order["city_express_state"] = 0;
                $order["diyformfields"] = iserializer([]);
                $order["diyformdata"] = '';
                $order["diyformid"] = 0;
                $order["address"] = iserializer($address);
                $order["ordersn2"] = 0;
                $order["order_source"] = 2;

                $resOrderP = static::mk()->create($order);
                $parentid = $resOrderP->id;
            }else{
                $parentid = 0;
            }
            $makeorderstatus = 1;
            foreach ($allgoods as $merchid => $goods) {
                $totalprice = 0;//订单实际支付金额 
                $totalpriceact = 0;

                //无主订单时候为单一订单计算优惠，否则以主订单优惠为主
                if ($parentid == 0) {
                    foreach ($goods as $k => $g) {
                        $totalprice += $g['marketprice']*$g['goods_number'];
                        if($g['isdiscount']==1){
                            //参加活动的商品金额
                            $totalpriceact += $g['marketprice']*$g['goods_number'];
                        }
                    }
                    $goodsprice = $totalprice;
                    $goodspriceact = $totalpriceact;
                    $weigoodsprice = $totalprice - $totalpriceact;
                    $actinfo  = ImsEweiShopActivity::mk()->where(['actstatus'=>1,'delete'=>0])->find();
                    if(!empty($actinfo) && $actinfo['acttype']==1){
                        if($goodspriceact>$actinfo['actcount']){
                            $discountprice =  $actinfo['actdiscount'];
                            $goodsprice =  $goodspric - $actinfo['actdiscount'];                    
                        }elseif($actinfo['acttype']==2){
                            $goodsprice = $weigoodsprice + $totalpriceact * $actinfo['actdiscount'];
                        }
                    }
                }else{
                    foreach ($goods as $k => $g) {
                        $totalprice += $g['marketprice']*$g['goods_number'];
                    }
                    $goodsprice = $totalprice;
                }

                $order = [];
                $ordersn = self::createNO("ordersn", "ME");

                $order["driver_id"] = 0;
                $order["ismerch"] = 1;
                $order["parentid"] = $parentid;
                $order["uniacid"] = 2;
                $order["openid"] = $member['openid'];
                $order["ordersn"] = $ordersn;
                $order["price"] = $totalprice;
                $order["oldprice"] = $totalprice;
                $order["grprice"] = $totalprice;
                $order["taskdiscountprice"] = 0;
                $order["lotterydiscountprice"] = 0;
                $order["discountprice"] = $discountprice;
                $order["isdiscountprice"] = $isdiscountprice;
                $order["merchisdiscountprice"] = $merchisdiscountprice;
                $order["dispatchprice"] = 0;
                $order["cash"] = 0;
                $order["status"] = 0;
                $order["remark"] = trim($datas["remark"]);
                $order["addressid"] = !empty($datas['address_id']) ? $datas['address_id'] : 0;
                $order["goodsprice"] = $goodsprice;
                $order["dispatchtype"] = 0;
                $order["dispatchid"] = 0;
                $order["storeid"] = 0;
                $order["carrier"] = iserializer($cart_list);
                $order["createtime"] = time();
                $order["olddispatchprice"] = 0;
                $order["contype"] = 0;
                $order["couponid"] = 0;
                $order["wxid"] = 0;
                $order["wxcardid"] = 0;
                $order["wxcode"] = '';
                $order["couponmerchid"] = 0;
                $order["paytype"] = 0;
                $order["deductprice"] = 0;
                $order["deductcredit"] = 0;
                $order["deductcredit2"] = 0;
                $order["deductenough"] = 0;
                $order["merchdeductenough"] = 0 ;
                $order["couponprice"] = 0;
                $order["merchshow"] = 0;
                $order["buyagainprice"] = 0;
                $order["ispackage"] = 0;
                $order["packageid"] = 0;
                $order["seckilldiscountprice"] = $seckill_price;
                $order["quickid"] = 0;
                $order["officcode"] = 0;
                $order["liveid"] = 0;
                $order["merchid"] = intval($merchid);
                $order["isparent"] = 0;
                $order["transid"] = 0;
                $order["isverify"] = $isverify ? 1 : 0;
                $order["verifytype"] = $verifytype;
                $order["verifyendtime"] = $endtime;
                $order["verifycode"] = '';
                $order["verifycodes"] = '';
                $order["verifyinfo"] = iserializer([]);
                $order["virtual"] = 0;
                $order["isvirtual"] = $isvirtual ? 1 : 0;
                $order["isvirtualsend"] = $isvirtualsend ? 1 : 0;
                $order["invoicename"] = '';
                $order["coupongoodprice"] = 0;
                $order["city_express_state"] = 0;
                $order["diyformfields"] = iserializer([]);
                $order["diyformdata"] = '';
                $order["diyformid"] = 0;
                $order["address"] = iserializer($address);
                $order["ordersn2"] = 0;
                $order["order_source"] = 2;

                $resOrder = static::mk()->create($order);
                $orderid = $resOrder->id;

                foreach ($goods as $k => $g) {
                    $order_goods = [];
                    $price_og = $g["marketprice"] * $g["goods_number"];
                    //利润
                    if ($g['service_fee_type'] == 1) {
                        $salesman_due = $g["service_fee_per"] * $g["goods_number"];
                    }elseif ($g['service_fee_type'] == 2) {
                        $salesman_due = ($g['costprice']*$g['costnum']*$g['service_fee_per']/100) * $g["goods_number"];
                    }else{
                        $salesman_due = $g["service_fee_per"] * $g["goods_number"];
                    }
                    //成本
                    $supplier_due = $g["costprice"] * $g['costnum'] * $g["goods_number"];
                    
                    $order_goods["parent_gid"] = $g["parent_gid"];
                    $order_goods["parent_merchid"] = $g["parent_merchid"];
                    $order_goods["parent_price"] = $price_og;
                    $order_goods["supplier_due"] = $supplier_due;
                    $order_goods["supplier_share_due"] = 0;
                    $order_goods["supplier_share_openid"] = '';
                    $order_goods["salesman_due"] = $salesman_due;
                    $order_goods["salesman_share_due"] = 0;
                    $order_goods['salesman_share_openid'] = '';
                    $order_goods["merchid"] = $g["merchid"];
                    $order_goods["merchsale"] = 0;
                    $order_goods["uniacid"] = 2;
                    $order_goods["orderid"] = $orderid;
                    $order_goods["goodsid"] = $g["goodsid"];
                    $order_goods["price"] = $price_og;
                    $order_goods["total"] = $g["goods_number"];
                    $order_goods["dispatchprice"] = 0;
                    $order_goods["optionid"] = 0;
                    $order_goods["createtime"] = time();
                    $order_goods["optionname"] = '';
                    $order_goods["title"] = $g["title"].$g["subtitle"];
                    $order_goods["goodssn"] = $g["goodssn"];
                    $order_goods["productsn"] = $g["productsn"];
                    $order_goods["realprice"] = $price_og;
                    $order_goods["consume"] = iserializer(array("consume_deduct" => 0, "consume_deduct2" => 0));
                    $order_goods["fullbackid"] = 0;
                    $order_goods["oldprice"] = $price_og;
                    $order_goods["isdiscountprice"] = 0;
                    $order_goods["openid"] = $member['openid'];
                    $order_goods["diyformid"] = 0;
                    $order_goods["diyformdata"] = false;
                    $order_goods["diyformfields"] = iserializer([]);
                    $order_goods["canbuyagain"] = 0;
                    $order_goods["seckill"] = 0;
                    $order_goods["seckill_taskid"] = 0;
                    $order_goods["seckill_roomid"] = 0;
                    $order_goods["seckill_timeid"] = 0;

                    $res = ImsEweiShopOrderGoods::mk()->create($order_goods);
                    ImsEweiShopMemberCart::mk()->update(['deleted' => 1], ['id' => $g['id']]);
                    $makeorderstatus = 2;
                }
            }
            static::mk()->commit();
        } catch (\Exception $e) {
            $makeorderstatus = 3;
            // 回滚事务
            static::mk()->rollback();
        }
        if (isset($orderid)) {
            return ['code'=>200,'message'=>'下单成功','parentid'=>$parentid,'orderid'=>$orderid];
        }else{
            return ['code'=>2000,'message'=>'下单失败','parentid'=>$parentid];
        }
    }

    public static function afterPayOrder($ordersn){
        if (empty($ordersn)) {
            return false;
        }
        //查询支付的订单信息
        $orderInfo = static::mk()->where(['ordersn'=>$ordersn])->findOrEmpty();
        if ($orderInfo->isEmpty()) return false;
        //支付订单为主订单时候需要同步更新子订单

        if ($orderInfo['parentid'] == 0 && $orderInfo['isparent'] == 1 ) {
            static::mk()->update(['status' => 1, 'paytype' => 21, 'paytime' => time(),'transid'=>$orderInfo['transid']], ['parentid' => $orderInfo['id']]);
        }
        return true;

    }

    public static function createNO($field, $prefix)
    {
        $billno = date('YmdHis') . random(6, true);
        while (1) {
            $count = static::mk()->where( $field , '=', $billno)->count();
            if ($count <= 0) {
                break;
            }
            $billno = date('YmdHis') . random(6, true);
        }
        return $prefix . $billno;
    }

    public static function checkStatus($id, $status)
    {
        if (empty($id) || empty($status)) {
            return false;
        }
        $updateData = [];
        $updateData['status'] = $status;
        $updateData['finishtime'] = time();
        return static::mk()->where( 'id' , '=', $id)->update($updateData);
    }

    public static function orderStatusStr($status){
        switch ($status) {
            case '0':
                $str = '待支付';
                break;
            case '1':
                $str = '待发货';
                break;
            case '2':
                $str = '待收货';
                break;
            case '3':
                $str = '已完成';
                break;
            case '30':
                //申请货到付款时候显示代发货
                $str = '待发货';
                break;
            case '-1':
                $str = '已关闭';
                break;
            default:
                $str = '其他';
                break;
        }
        return $str;
    }

    public static function orderPaytypeStr($status,$paytype){
        if ($status==0) {
            return '-';
        }elseif ($status == -1) {
            // return '订单关闭';
        }elseif ($status == 30 && $paytype == 0) {
            return '货到付款';
        }
        switch ($paytype) {
            case '21':
                $str = '微信支付';
                break;
            case '1':
                $str = '货到付款';
                break;
            default:
                $str = '其他';
                break;
        }
        return $str;
    }

    public static function getActionArr($status,$isInofo = 0){
        if ($isInofo == 0) {
            $info = ['订单详情'];
        }elseif($isInofo == 1 && $status == 3){
            $info = ['删除订单'];
        }else{
            $info = [];
        }
        switch ($status) {
            case '0':
                $arr = ['立即支付','取消订单'];
                break;
            case '1':
                $arr = [];
                break;
            case '2':
                $arr = ['确认收货'];
                break;
            case '3':
                $arr = [];
                break;
            case '-1':
                $arr = [];
                break;
            default:
                $arr = [];
                break;
        }
        if (!empty($info)) {
            $arr = $arr+$info;
        }
        return $arr;
    }


    /**
     * @param $id
     * @return mixed
     * @author du
     * @date 2025/4/17
     */
    public static function wechatSend($orderid){

        //配置后期加在env里或者config
        $config_arr = WechatService::getWxconf();
        $config = [
            'app_id' => $config_arr['appid'],
            'secret' => $config_arr['appsecret'],
            'mch_id' => $config_arr['appsecret'],
            'log' => [
                'level' => 'debug',
            ]
        ];

        $app = new Application($config);

        try {
            // 1. 获取请求参数
            $orderinfo = static::mk()->where(['id'=>$orderid])->findOrEmpty();
            if ($orderinfo->isEmpty()) throw new \Exception('订单不存在！');//$this->error('订单不存在！');
            error_log('SEND_ORDER_ID:'.$orderinfo['id']);
            if ($orderinfo['status'] != 1) {
                return json_encode(['code' => 0, 'msg' => '订单已经发货'],JSON_UNESCAPED_UNICODE);
            }
            if ($orderinfo['paytype'] != 21) {
                return json_encode(['code' => 0, 'msg' => '非微信小程序支付不用远程发货'],JSON_UNESCAPED_UNICODE);
            }
            //有父id时候发最后一件货时候调用微信发货接口通知客户
            if ($orderinfo['parentid'] > 0) {
                $count = static::mk()->where(['parentid'=>$orderinfo['parentid'],'status'=>1])->count();
                if ($count > 1) {
                    return json_encode(['code' => 0, 'msg' => '还有其他未发货订单，后续一起发货'],JSON_UNESCAPED_UNICODE);
                }
            }
            error_log('SEND_ORDER_ID:'.$orderinfo['id']);
            $orderGoodList = ImsEweiShopOrderGoods::mk()->where(['orderid'=>$orderinfo['id']])->select();
            $item_desc = '';
            foreach ($orderGoodList as $k => $v) {
                $item_desc .= $v['title'].';';
            }
            // 2. 验证必要参数
            if (empty($orderinfo['ordersn']) || empty($orderinfo['openid']) || empty($orderinfo['transid'])) {
                throw new \Exception('缺少必要参数');
            }
            $record = WechatPaymentRecord::mk()->where('payment_trade','=',$orderinfo['transid'])->findOrEmpty();
            if ($record->isEmpty()) throw new \Exception('支付单不存在！');//$this->error('支付单不存在！');
            error_log('SEND_RECORD_ID:'.$record['id']);     
            $accessToken = $app->getAccessToken();
            $access_token = $accessToken->getToken(); // string
            $api = $app->getClient();
            $url_o = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=".$access_token;
            error_log('SEND_URL:'.$url_o);
            $orderDetail = [
                "order_key" => [
                    "order_number_type" => 2,
                    "transaction_id" => $record['payment_trade'],
                    "mchid"=>"1711684005",
                    "out_trade_no"=>$record['code']
                ],
                "logistics_type" => 2,
                "delivery_mode" => 1,
                 "shipping_list" => [
                    [
                         "item_desc" => $item_desc
                    ]
                ],
                "upload_time" => date('Y-m-d\TH:i:sP'),
                "payer" => [
                    'openid'=>$orderinfo['openid']
                ]
            ];
            error_log('SEND_DATA:'.json_encode($orderDetail));
            $result = $api->post($url_o, [
                    'json' => json_encode($orderDetail,JSON_UNESCAPED_UNICODE)
                ]
            );
            error_log('SEND_RESULT:'.$result['errcode'].$result['errmsg'].$orderid);
            if (isset($result['errcode']) && isset($result['errmsg'])) {
                return json_encode(['code' => $result['errcode'], 'msg' => $result['errmsg']],JSON_UNESCAPED_UNICODE);
            }else{
                return json_encode(['code' => 1, 'msg' => 'accessError']);
            }
        } catch (\Exception $e) {
            return json_encode(['code' => 1, 'msg' => $e->getMessage()],JSON_UNESCAPED_UNICODE);
        }

    }

 
}